package com.hemaapp.yjnh.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseAdapter;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.CunyouAreaAdapter;
import com.hemaapp.yjnh.adapter.CunyouDistrictAdapter;
import com.hemaapp.yjnh.adapter.HotAreaAdapter;
import com.hemaapp.yjnh.bean.HotDistrict;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.bean.ZouzouDistrict;
import com.hemaapp.yjnh.view.YJNHDrawerLayout;
import com.hemaapp.yjnh.view.YjnhGridView;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomListView;

public class CunyouActivity extends BaseActivity implements OnClickListener {

    private YJNHDrawerLayout mDrawerLayout;
    private LinearLayout ll_zouzou_area;
    private TextView titleText;
    private ImageButton titleLeft;
    private Button titleRight;
    private ImageView titleSearch;

    private XtomListView listProvince;
    private XtomListView listview_info;
    private TextView tvCity;
    private XtomListView listArea;

    private View headerView;
    private YjnhGridView gridView;//用于加载村游热门图片

    private ProvinceAdapter provinceAdapter;//省份适配器
    private ArrayList<ZouzouDistrict> mProvinces = new ArrayList<>();//省份直辖市自治区列表
    private ArrayList<HotDistrict> hotDistricts = new ArrayList<HotDistrict>();//热门区域
    private ArrayList<ZouzouDistrict> areas = new ArrayList<ZouzouDistrict>();//省县区列表
    private String location = "";//当前所在的城市，用于获取周边
    private HotAreaAdapter hotAreaAdapter;//热门下的区域列表
    private HotAreaAdapter cunyouHotAdapter;//地方城市热门区域列表
    private CunyouDistrictAdapter districtAdapter;//省级下面地级市列表适配器
    private CunyouAreaAdapter areaAdapter;//地级市下面的县区列表适配器
    private int hotPage = 0;//村游热门区域的page
    private User user;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.fragment_zouzou_drawer);
        super.onCreate(savedInstanceState);
        user = getApplicationContext().getUser();
        init();
    }

    private void init() {
        location = XtomSharedPreferencesUtil.get(mContext, "province");
        //获取省级名称
        String token = user == null ? "" : user.getToken();
        getNetWorker().zouzouDistrictList(token, "1", "无");
        //初始化村游热门的header图片
        headerView = LayoutInflater.from(mContext).inflate(R.layout.listitem_zouzou_district_header, null);
        gridView = (YjnhGridView) headerView.findViewById(R.id.gridview);
    }

    private void getCityList(String name) {
        String token = user == null ? "" : user.getToken();
        getNetWorker().zouzouDistrictList(token, "2", name);
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case TRAVEL_ADDRESS_LIST:
            case HOTDISTRICT_LIST:
                showProgressDialog("请稍候");
                break;
            default:
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case TRAVEL_ADDRESS_LIST:
            case HOTDISTRICT_LIST:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case TRAVEL_ADDRESS_LIST:
                String type = netTask.getParams().get("keytype");
                HemaPageArrayResult<ZouzouDistrict> zResult = (HemaPageArrayResult<ZouzouDistrict>) baseResult;
                if (zResult == null || zResult.getObjects() == null)
                    return;
                if (type.equals("1")) {//获取的是省级列表,只有在第一次时加载
                    mProvinces.clear();
                    ZouzouDistrict hotDistrict = new ZouzouDistrict();
                    hotDistrict.setProvince_name("热门");
                    hotDistrict.setChecked(true);
                    mProvinces.add(hotDistrict);
                    ZouzouDistrict surDistrict = new ZouzouDistrict();
                    surDistrict.setProvince_name("周边");
                    mProvinces.add(surDistrict);
                    mProvinces.addAll(zResult.getObjects());
                    //获取当前所在省份的简称
                    //获取简称的算法：取当前定位城市的前两个字，然后和已获取的省份列表中省份的前两个字挨个匹配
                    String prov1 = location.substring(0, 2);
                    for (int i = 0; i < mProvinces.size(); i++) {
                        String province = mProvinces.get(i).getprovince_name().substring(0, 2);
                        if (province.equals(prov1)) {
                            location = mProvinces.get(i).getprovince_name();
                            break;
                        }
                    }
                    getHotAreaList("");//获取完省份之后，默认去加载热门里的走走信息
                    refreshProcince();//刷新省份
                } else if (type.equals("2")) {//获取的是省份下面的城市
                    areas.clear();
                    areas.addAll(zResult.getObjects());
                    freshArea(-1);
                }
                break;
            case HOTDISTRICT_LIST:
                String keyid = netTask.getParams().get("keyid");//获取热门区域时的省份名称，如果不为空，则表示为省份下的热门村游；为空表示大分类下的热门村游
                HemaPageArrayResult<HotDistrict> dResult = (HemaPageArrayResult<HotDistrict>) baseResult;
                if (dResult == null || dResult.getObjects() == null)
                    return;
                ArrayList<HotDistrict> areas = dResult.getObjects();
                hotDistricts.clear();
                hotDistricts.addAll(areas);
                if (isNull(keyid)) {//大分类下(与省份同级)的热门村游
                    refreshHotArea(-1);
                } else {
                    refreshHotCunyou();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case TRAVEL_ADDRESS_LIST:
            case HOTDISTRICT_LIST:
                XtomToastUtil.showShortToast(mContext, "获取信息失败," + baseResult.getMsg());
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case TRAVEL_ADDRESS_LIST:
            case HOTDISTRICT_LIST:
                XtomToastUtil.showShortToast(mContext, "获取信息失败,请稍后再试");
                break;
            default:
                break;
        }
    }

    private void refreshProcince() {
        if (provinceAdapter == null) {
            provinceAdapter = new ProvinceAdapter(mContext, mProvinces);
            listProvince.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    for (ZouzouDistrict district : mProvinces) {
                        district.setChecked(false);
                    }
                    mProvinces.get(position).setChecked(true);
                    provinceAdapter.notifyDataSetChanged();
                    if (position == 0) {//点击的是热门区域
                        //将分辨率从dp转成px
                        int div_hei = BaseUtil.dip2px(mContext, 1);
                        listview_info.setDividerHeight(div_hei);
                        getHotAreaList("");
                    } else if (position == 1) {//点击的是周边
                        //先去获取村游热门的图片
                        getHotAreaList(location);
                        //再去获取这个省份下面的城市
                        getCityList(location);
                        listview_info.setDividerHeight(1);//分割线高度一个像素
                    } else {//点击的是具体省份
                        String province = mProvinces.get(position).getprovince_name();
                        getHotAreaList(province);//获取村游图片
                        getCityList(province);//获取这个省份下的城市列表
                        listview_info.setDividerHeight(1);//分割线高度一个像素
                    }
                }
            });
            listProvince.setAdapter(provinceAdapter);
        }else {
            provinceAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 热门城市
     *
     * @param failedType
     */
    private void refreshHotArea(int failedType) {
        if (listview_info.getHeaderViewsCount() > 0) {
            listview_info.removeHeaderView(headerView);
        }
        if (hotAreaAdapter == null) {
            hotAreaAdapter = new HotAreaAdapter(mContext, hotDistricts, 1);
            hotAreaAdapter.setEmptyString("暂无更多地区");
            listview_info.setAdapter(hotAreaAdapter);
        } else {
            listview_info.setAdapter(hotAreaAdapter);//这里要多设一遍
            hotAreaAdapter.setEmptyString("暂无更多地区");
            hotAreaAdapter.notifyDataSetChanged();
        }
        hotAreaAdapter.setFailtype(failedType);
    }

    /**
     * 地方村游的热门图片
     */
    private void refreshHotCunyou() {
        if (cunyouHotAdapter == null) {
            cunyouHotAdapter = new HotAreaAdapter(mContext, hotDistricts, 3);
            cunyouHotAdapter.setEmptyString("暂无热门景点");
            cunyouHotAdapter.setShowEmpty(false);
            gridView.setAdapter(cunyouHotAdapter);
        } else {
            gridView.setAdapter(cunyouHotAdapter);//这里要多设一遍
            cunyouHotAdapter.setEmptyString("暂无热门景点");
            cunyouHotAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 省份下面的城市列表
     *
     * @param failedType
     */
    private void freshArea(int failedType) {
        if (listview_info.getHeaderViewsCount() > 0) {
            listview_info.removeHeaderView(headerView);
        }
        listview_info.setAdapter(null);
        listview_info.addHeaderView(headerView);
        if (districtAdapter == null) {
            districtAdapter = new CunyouDistrictAdapter(this, areas);
            districtAdapter.setEmptyString("暂无更多地区");
            listview_info.setAdapter(districtAdapter);
        } else {
            listview_info.setAdapter(districtAdapter);//这里要多设一遍
            districtAdapter.setEmptyString("暂无更多地区");
            districtAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取热门区域
     * 大分类下的热门区域
     */
    private void getHotAreaList(String area) {
        getNetWorker().hotDistrictList("2", area, hotPage + "");
    }

    @Override
    protected void findView() {
        mDrawerLayout = (YJNHDrawerLayout) findViewById(R.id.main_drawer_layout);
        ll_zouzou_area = (LinearLayout) findViewById(R.id.ll_zouzou_area);
        titleText = (TextView) findViewById(R.id.title_text);
        titleLeft = (ImageButton) findViewById(R.id.title_left_btn);
        titleRight = (Button) findViewById(R.id.title_right_btn);
        titleSearch = (ImageView) findViewById(R.id.title_right_img);

//		ll_city = (LinearLayout) findViewById(R.id.ll_city);
        listProvince = (XtomListView) findViewById(R.id.list_province);
        listview_info = (XtomListView) findViewById(R.id.listview_info);
        tvCity = (TextView) findViewById(R.id.tv_city);
        listArea = (XtomListView) findViewById(R.id.list_area);
    }

    @Override
    protected void setListener() {
        titleText.setText("村游");
        titleLeft.setOnClickListener(this);
        titleRight.setVisibility(View.GONE);
        titleSearch.setVisibility(View.VISIBLE);
        titleSearch.setOnClickListener(this);
    }

    /**
     * 打开侧滑
     */
    public void openDrawer(ZouzouDistrict district) {
        if (mDrawerLayout.isDrawerOpen(ll_zouzou_area)) {
            mDrawerLayout.closeDrawer(ll_zouzou_area);
        } else {
            tvCity.setText(district.getcity_name());
            mDrawerLayout.openDrawer(ll_zouzou_area);
            if (areaAdapter == null) {
                areaAdapter = new CunyouAreaAdapter(this, district.gettowns());
                areaAdapter.setEmptyString("该地区下暂无信息");
                listArea.setAdapter(areaAdapter);
            } else {
                areaAdapter.setTowns(district.gettowns());
                areaAdapter.setEmptyString("该地区下暂无信息");
                areaAdapter.notifyDataSetChanged();
            }
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_img:
                Intent itSearch = new Intent(mContext, SearchActivity.class);
                itSearch.putExtra("type", 5);
                itSearch.putExtra("assort", "村游");
                startActivity(itSearch);
                break;
        }
    }

    public class ProvinceAdapter extends BaseAdapter {

        ArrayList<ZouzouDistrict> datas;

        public ProvinceAdapter(Context context, ArrayList<ZouzouDistrict> datas) {
            super(context);
            this.datas = datas;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {
            return datas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (isEmpty())
                return getEmptyView(parent);
            ViewHolder holder;
            if (convertView == null || convertView.getTag(R.id.TAG_VIEWHOLDER) == null) {
                convertView = LayoutInflater.from(mContext).inflate(
                        R.layout.item_cunyou_province, parent, false);
                holder = new ViewHolder(convertView);
                convertView.setTag(R.id.TAG_VIEWHOLDER, holder);
            } else
                holder = (ViewHolder) convertView.getTag(R.id.TAG_VIEWHOLDER);
            holder.setDatas(position);
            return convertView;
        }

        class ViewHolder {
            @Bind(R.id.tab_bar)
            View tabBar;
            @Bind(R.id.iv_assort)
            ImageView ivAssort;
            @Bind(R.id.tv_province)
            TextView tvProvince;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }

            private void setDatas(int position) {
                ZouzouDistrict district = datas.get(position);
                tvProvince.setText(district.getprovince_name());
                if (district.isChecked()) {
                    tabBar.setVisibility(View.VISIBLE);
                    tvProvince.setTextColor(mContext.getResources().getColor(R.color.text_orange));
                    if (position == 0)
                        ivAssort.setImageResource(R.drawable.ic_cunyou_hot_s);
                    else if (position == 1)
                        ivAssort.setImageResource(R.drawable.ic_cunyou_surround_s);
                }else {
                    tabBar.setVisibility(View.GONE);
                    tvProvince.setTextColor(mContext.getResources().getColor(R.color.text_color_dark_grey));
                    if (position == 0)
                        ivAssort.setImageResource(R.drawable.ic_cunyou_hot_n);
                    else if (position == 1)
                        ivAssort.setImageResource(R.drawable.ic_cunyou_surround_n);
                }
            }
        }
    }
}
